# coding=utf-8
'''
手写识别
'''
from numpy import *
from os import listdir
import operator
import random

def readFile(filename):
    data=zeros((1,1024))
    fr=open(filename)
    for i in range(32):
        line=fr.readline()
        for j in range(32):
            data[0,32*i+j]=int(line[j])
    return data


def classify(testData,dataSet,labels,k):
    red = (dataSet - testData) ** 2
    s = red.sum(axis=1)
    distance = (s ** 0.5).argsort()
    index= distance[0]
    classCount={}
    for i in range(k):
        vlabel=labels[distance[i]]
        classCount[vlabel]=classCount.get(vlabel,0)+1
    re=sorted(classCount.iteritems(),key=operator.itemgetter(1),reverse=True)
    return re[0][0]
    return (labels[distance])[0]

classCount={}
for i in range(3):
    classCount[i]=classCount.get(i,0)+1
    print classCount

def readDir(dirName):
    listFile = listdir(dirName)
    length = len(listFile)
    group = zeros((length, 1024))
    labels = []

    index = 0
    for filename in listFile:
        labels.append(int(filename.split('.')[0].split('_')[0]))
        index += 1

    for i in range(length):
        group[i]=readFile(dirName+'\\'+listFile[i])
    return group,labels


def handWritingTest():
    error = 0.0
    traingMat,traingLabels=readDir('digits\\trainingDigits')
    testMat,testLabels=readDir('digits\\testDigits')

    m=len(testMat)
    for i in range(m):
        cl=classify(testMat[i],traingMat,traingLabels,3)
        print cl,testLabels[i]
        # print testLabels[i]
        print "---------"
        if cl!=testLabels[i]:
            error+=1
    print error
    print error/m

# print operator.itemgetter(1)

# handWritingTest()
# print classify(testSet,dataSet,['A','B','C'],3)
# handWritingTest()
# print readFile('digits\\trainingDigits\\0_0.txt')
